<template>
    <div class="main">
        <div class="topTitle">{{ props.title }}</div>
        <div class="form_content">
            <NScrollbar>
                <NSpin :show="spinShow">
                    <div class="content">
                        <!-- <div class="progressHint" v-if="hint">
                            <NIcon size="20" class="iconStyle">
                                <ErrorRound />
                            </NIcon>
                            <div style="white-space: pre-wrap" v-html="hint"></div>
                        </div>
                        <div class="progress">
                            <div style="display:flex; margin-right: 10rem;">
                                <NIcon :size="20" class="iconStyle">
                                    <ApprovalFilled />
                                </NIcon>
                                <span>审批流程</span>
                            </div>
                            <span style="font-size: 18rem;flex: 1;"
                                :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
                            </span>
                        </div> -->
                        <div class="content_cen">
                            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules"
                                :label-width="110" :model="formValue" label-align="right" style="width: 350rem;">

                                <NFormItem label="资产名称:" path="assetName">
                                    <NInput placeholder="请输入资产名称" class="commonWidth"
                                        v-model:value="formValue.assetName" clearable />
                                </NFormItem>

                                <NFormItem label="资产类目:" path="categoriesId">
                                    <NTreeSelect :options="categoryList" v-model:value="formValue.categoriesId"
                                        label-field="categoriesName" key-field="id"
                                        children-field="childList" />
                                </NFormItem>

                                <template v-if="formType === 'AssetDetailEdit'">
                                    <NFormItem label="使用人:" path="userId">
                                        <NSelect :options="userList" filterable v-model:value="formValue.userId" />
                                    </NFormItem>
                                    <NFormItem label="旧资产编码:" path="oldAssetNumber">
                                        <NInput class="commonWidth" v-model:value="formValue.oldAssetNumber" readOnly
                                            :disabled="true" />
                                    </NFormItem>
                                    <NFormItem label="状态:" path="status">
                                        <NSelect :options="statusOptions" v-model:value="formValue.status" />
                                    </NFormItem>
                                    <NFormItem label="可否领用:" path="requisitionFlag">
                                        <NSelect :options="requisitionFlagOptions"
                                            v-model:value="formValue.requisitionFlag" />
                                    </NFormItem>
                                </template>

                                <NFormItem label="库房位置:" path="warehouseId">
                                    <NTreeSelect :options="warehouseList" v-model:value="formValue.warehouseId"
                                        label-field="warehouseName" key-field="id" children-field="childList" />
                                </NFormItem>

                                <template v-if="formType === 'AssetDetailEdit'">
                                    <NFormItem label="初始库房位置:" path="initialWarehouseId">
                                    <NTreeSelect :options="warehouseList" v-model:value="formValue.initialWarehouseId"
                                        label-field="warehouseName" key-field="id" children-field="childList" :disabled="true"/>
                                </NFormItem>
                                </template>

                                <NFormItem label="数量:" path="con" v-if="formType === 'AssetsAdd'">
                                    <NInput :allow-input="onlyNumber" v-model:value="formValue.con" />
                                </NFormItem>

                                <NFormItem label="备注:" path="remark">
                                    <NInput placeholder="请输入备注" style="min-height: 100rem" type="textarea"
                                        v-model:value="formValue.remark" clearable class="commonWidth"
                                        :allow-input="noSideSpace" />
                                </NFormItem>


                            </NForm>
                        </div>
                    </div>
                </NSpin>
            </NScrollbar>
        </div>
    </div>
    <FixedAction>
        <div style="display: flex;justify-content: center;align-items: center;">
            <NSpace>
                <NButton style="width: 80px; color: #5fb17f" ghost @click="goBack">
                    <template #icon>
                        <img :src="VBackImg" style="width: 25rem; height: 25rem" />
                    </template>
                    返回
                </NButton>
                <NButton type="primary" style="width: 80px;" @click="confirm" :loading="loading">
                    保存
                </NButton>
            </NSpace>
        </div>
    </FixedAction>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
    NSpace,
    NForm,
    NInput,
    NFormItem,
    NSelect,
    NButton,
    NScrollbar,
    NModal,
    NIcon,
    useMessage,
    NSpin,
    NTreeSelect,
    NInputNumber,
    type FormInst
} from 'naive-ui'
import router from '@/router'
import { onMounted, computed } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import VScope from '@/views/OA/Common/Scope.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import { CloseFilled } from '@vicons/material'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { subDays } from 'date-fns'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'

//只能输入两位数字
const onlyNumber = (value: string) => {
    var regA = /^\d*\.{0,1}\d{0,2}$/
    return !value || regA.test(value)
}

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
    title: { type: String, default: () => '' },
    id: { required: false, type: [Number, String], default: null },
    type: { required: true, type: String, default: "AssetsAdd" },
    flat: { default: () => false }
})
/** 表单类型
 * AssetsAdd：资产列表新增（默认）
 * AssetDetailEdit：资产详情编辑
 */
const formType = ref("AssetsAdd")
const message = useMessage()
const mockData = [
    {
        label: '父1', key: '父1', children: [
            { label: '父1-子1', key: '父1-子1' },
            { label: '父1-子2', key: '父1-子2' },
        ]
    },
    {
        label: '父2', key: '父2', children: [
            { label: '父2-子1', key: '父2-子1' },
            { label: '父2-子2', key: '父2-子2' },
        ]
    }
]
const requisitionFlagOptions = [
    { value: 1, label: "是" },
    { value: 0, label: "否" }
]
const statusOptions = [
    { value: 0, label: '在库' },
    { value: 1, label: '使用中' },
    { value: 2, label: '停用' },
]
const formValue = reactive<Record<string, any>>({
    assetName: null, // 资产名称
    assetNumber: null, // 资产编号
    categoriesId: null, // 资产类目id
    warehouseId: null, // 存放位置id
    initialWarehouseId: null, // 初始存放位置id
    con: "1", // 数量
    remark: null, // 备注
    draftFlag: null, //草稿状态
    entityId: null, //流程实体id
    status: null,
    oldAssetNumber: null, // 旧资产编码
    requisitionFlag: null, // 是否可领用
    userId: null, // 使用人
})
const rules = {
    assetName: {
        required: true,
        message: '请输入资产名称',
        trigger: ['input', 'change', 'blur']
    },
    categoriesId: {
        required: true,
        message: '请选择资产类目',
        trigger: ['select', 'change']
    },
    warehouseId: {
        required: true,
        message: '请选择存放位置',
        trigger: ['select', 'change']
    },
    initialWarehouseId: {
        required: true,
        message: '请选择存放位置',
        trigger: ['select', 'change']
    },
    con: {
        required: true,
        message: '请输入数量',
        trigger: ['input', 'change', 'blur']
    },
    remark: {
        required: false,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (value?.length > 500) return new Error('备注字数不得超过500')
            return true
        }
    },
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')

// 获取流程id
const hint = ref()
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
    const [error, res] = await sendRequest({
        module: 'receiveOrDispatch',
        api: 'workFlow',
        override: {
            params: {
                functionCode: 'A0502'
            }
        }
    })
    if (error) return
    if (res.code !== 0) return
    formValue.entityId = res.data.entityId
    hint.value = res.data.remark
    workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
}
// 返回
const goBack = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
    tags.splice(index, 1)
    if (tags.length == 0) {
        router.push({ path: '/OA/Workbench/UserDesktop' })
    } else history.back()
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)

// 保存
const confirm = (status: any) => {
    formRef.value?.validate(async (err) => {
        if (err) return false
        if (formType.value === "AssetsAdd") {
            handleAssetsAdd()
        } else if (formType.value === "AssetDetailEdit") {
            handleAssetsDetailEdit()
        }
    })
}
const handleAssetsAdd = async () => {
    loading.value = true
    loading.value = true
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'saveAssets',
        override: {
            data: {
                ...formValue,
                con: Number(formValue.con)
            }
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    if (res.code === 0) {
        message.success("保存成功")
        loading.value = false
        setTimeout(() => {
            goBack()
        }, 500)
    }
}
/** 资产详情的编辑 */
const handleAssetsDetailEdit = async () => {
    loading.value = true
    const userResult = userList.value.find((v: any) => {
        return v.value === formValue.userId
    })
    let categoriesName = null
    let warehouseName = null
    let initialWarehouseName = null
    // 拿资产类目名，位置名等等
    if(![null, undefined].includes(formValue.categoriesId)) {
        categoriesName = await getCategoriesName(categoryList.value, String(formValue.categoriesId), {
            value: 'id',
            label: 'categoriesName',
            children: 'childList'
        })
    }
    if(![null, undefined].includes(formValue.warehouseId)) {
        warehouseName = await getCategoriesName(warehouseList.value, String(formValue.warehouseId), {
            value: 'id',
            label: 'warehouseName',
            children: 'childList'
        })
    }
    if(![null, undefined].includes(formValue.initialWarehouseId)) {
        initialWarehouseName = await getCategoriesName(warehouseList.value, String(formValue.initialWarehouseId), {
            value: 'id',
            label: 'warehouseName',
            children: 'childList'
        })
    }
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'updateAssets',
        override: {
            data: {
                id: props.id,
                ...formValue,
                categoriesName,
                warehouseName,
                initialWarehouseName,
                userName: userResult ? userResult.label : null,
                requisitionFlag: Boolean(formValue.requisitionFlag)
            }
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    if (res.code === 0) {
        message.success("保存成功")
        loading.value = false
        setTimeout(() => {
            goBack()
        }, 500)
    }
}
const getCategoriesName = (inirData: any, id: string, options: any) => {
    const { value, label, children } = options
    return new Promise((resolve, reject) => {
        const find = (data: any) => {
            data.forEach((c: any) => {
                if(String(c[value]) === id) {
                    resolve(c[label])
                }
                if(c[children] && c[children].length > 0) {
                    find(c[children])
                }
            })
        }
        find(inirData)
    })
}
// 提交
const contentVisible = ref(false)

//提交完跳转我的提交
const goSubmit = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
    tags.splice(index, 1)
    if (formValue.draftFlag) return router.push({ path: '/OA/UserCenter/Drafts' })
    router.push({ path: '/OA/UserCenter/Submit' })
}
/** 获取资产详情 */
const getAssetsDetail = async (id: number) => {
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'getAssetInfo',
        uri: {
            id
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    Object.keys(formValue).map((it: any) => {
        if (it === 'requisitionFlag') {
            formValue[it] = res.data.requisitionFlag ? 1 : 0
        } else if (it === 'userId') {
            formValue[it] = res.data.userId ? String(res.data.userId) : null
        } else {
            formValue[it] = res.data[it]
        }
    })
}
const userList = ref<any>([])
/** 获取使用人下拉 */
const getUserList = async () => {
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'getUserList',
        override: {
            data: {}
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    userList.value = res.data.map((item: any) => {
        return {
            value: item.value,
            label: item.name
        }
    })
}
const warehouseList = ref<any>([])
/** 获取位置下拉 */
const getWarehouseList = async () => {
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'getWarehouseList',
        override: {
            data: {}
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    warehouseList.value = res.data
}
const categoryList = ref<any>([])
/** 获取类目下拉 */
const getCategoryList = async () => {
    const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'assetsManagement',
        api: 'getCategoryList',
        override: {
            data: {}
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    categoryList.value = res.data
}

onMounted(async () => {
    spinShow.value = true
    await getCategoryList(); // 类目
    await getWarehouseList(); // 位置
    props.type === 'AssetDetailEdit' && await getUserList(); // 位置
    // await getWorkFlow();
    formType.value = props.type
    if (['AssetDetailEdit'].includes(props.type)) {
        props.id && await getAssetsDetail(Number(props.id))
        spinShow.value = false
    }
    spinShow.value = false
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
    font-size: 16rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
    width: 240rem;
}

.main {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .topTitle {
        width: 100%;
        border-bottom: 1px solid #fff;
        padding: 15rem 20rem;
        margin-bottom: 20rem;
        @include CommonFont;
    }

    .form_content {
        width: 100%;
        height: 100%;
        padding: 0 20rem 0rem;

        .content {
            display: flex;
            flex-wrap: wrap;
            padding: 20rem 0 180rem;
            background-color: #ebeceb;


            .scope {
                display: flex;
                flex-wrap: wrap;
                width: 100%;

                .userBox {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;
                    height: 40rem;
                    background-color: #fff;
                    border-radius: 4rem;
                    padding: 5px 10rem;
                    margin-bottom: 10rem;
                }
            }
        }
    }
}

.content_cen {
    display: flex;
    flex-direction: column;
    margin-left: 35%;
}

.iconStyle {
    margin-right: 5rem;
    color: #5fb17f;
}

.progress {
    display: flex;
    align-items: center;
    min-width: 350rem;
    max-width: 800rem;
    min-height: 50rem;
    background-color: #d5e2d8;
    border-radius: 5rem;
    margin-bottom: 10px;
    padding: 5px 15px;
    margin-left: 35%;
}

.progressHint {
    display: flex;
    min-width: 350rem;
    max-width: 800rem;
    padding: 5px 15px;
    margin-left: 35%;
}

.content::-webkit-scrollbar {
    display: none;
}

:deep(.n-spin-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-scrollbar-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-spin-content) {
    width: 100%;
    height: 100%;
}
</style>